package com.zheng.business.web.interceptor;

import com.zheng.common.util.RedisUtil;
import com.zheng.common.util.RequestUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lvg EMIAL：<a href="mailto:weiguo.liang@gh-ca.com">weiguo.liang@gh-ca.com</a> <br>
 * @version 1.0 <br>
 * @Company: GH-CA<br>
 * @ClassName: UpmsTaskInterceptor <br>
 * @Description: TODO <br>
 * @date 2019/8/5 17:21<br>
 **/
public class BusinessTaskInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(BusinessTaskInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("x-task-token");
        String timestamp = request.getHeader("timestamp");
        String ip = RequestUtil.getIpAddr(request);
        // 本地请求并且时间戳对上才可执行
        if(StringUtils.isNotBlank(token) &&
                StringUtils.isNotBlank(timestamp) &&
                "127.0.0.1".equals(ip) &&
                timestamp.equals(RedisUtil.get(token))
        ) {
            return true;
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
}
